import { payOrderApi, payOrderDetailApi } from '@/services/order'
import type { OrderItem } from '@/types/order'
import {
  closeToast,
  showConfirmDialog,
  showLoadingToast,
  showToast
} from 'vant'
import { onMounted, ref } from 'vue'
import type { Router } from 'vue-router'

import { useClipboard } from '@vueuse/core'

const { copy, isSupported } = useClipboard()

export function detail(orderId: string, router: Router) {
  const orderDetail = ref<OrderItem>()
  async function payOrderDetail() {
    const { data } = await payOrderDetailApi({ orderId })
    orderDetail.value = data
  }

  const showPay = ref(false)

  const payMethods = ref<0 | 1>()

  function submit() {
    showPay.value = true
  }

  async function onPayOrder() {
    if (payMethods.value === undefined) return showToast('请选择支付方式')
    const payOrderParams = {
      orderId: orderDetail.value!.id,
      payCallback: 'http://localhost:5173/room',
      paymentMethod: payMethods.value
    }
    try {
      showLoadingToast({
        message: '跳转支付',
        duration: 0,
        forbidClick: true
      })
      const { data } = await payOrderApi(payOrderParams)
      location.href = data.payUrl
    } catch (error) {
      console.log(error)
    } finally {
      closeToast()
    }
  }

  const onClose = () => {
    showConfirmDialog({
      title: '关闭支付',
      message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
      cancelButtonText: '仍要关闭',
      confirmButtonText: '继续支付'
    })
      .then(() => {
        return false
      })
      .catch(() => {
        router.push('/user/consult')
        return true
      })
  }

  const onCopy = async () => {
    if (!isSupported.value) return showToast('未授权，不支持')
    await copy(orderDetail.value?.orderNo || '')
    showToast('已复制')
  }

  onMounted(() => {
    payOrderDetail()
  })

  return {
    orderDetail,
    submit,
    showPay,
    payMethods,
    onPayOrder,
    onClose,
    onCopy
  }
}
